package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 阻塞模式下
 * @author glogo
 *
 */
public class EchoServer1 {

	private int port = 8000;
	private ServerSocketChannel serverSocketChannel = null;
	private ExecutorService executorService = null;
	private static int POOL_SIZE = 4;
	
	public EchoServer1() throws IOException{
		executorService = Executors.newFixedThreadPool(
				Runtime.getRuntime().availableProcessors() * POOL_SIZE);
		
		serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().setReuseAddress(true);
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		System.out.println("服务器启动");
	}
	
	public static void main(String[] args) throws IOException{
		new EchoServer1().service();
	}
	
	public void service(){
		while(true){
			SocketChannel socketChannel = null;
			try{
				socketChannel = serverSocketChannel.accept();
				executorService.execute(new Handler(socketChannel));
			}catch(IOException ioe){
				ioe.printStackTrace();
			}
		}
	}
	
	class Handler implements Runnable{

		private SocketChannel socketChannel = null;
		
		public Handler(SocketChannel socketChannel) {
			this.socketChannel = socketChannel;
		}
		
		@Override
		public void run() {
			handle(socketChannel);
		}
		
		private void handle(SocketChannel socketChannel){
			try{
				Socket socket = socketChannel.socket();
				System.out.println("接受到客户的连接：" + socket.getInetAddress() + ":" + socket.getPort());

				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter pw = new PrintWriter(socket.getOutputStream());
				
				//利用br与pw进行响应
				
			}catch(IOException ioe){
				ioe.printStackTrace();
			}finally{
				try{
					if(socketChannel != null) socketChannel.close();
				}catch(IOException ioe){
					ioe.printStackTrace();
				}
			}
			
		}
		
	}
	
}
